#coding:utf-8
# Echo server program -liujian
import socket
import time
import os
import threading

class DailyrunReporter:    
    def excutecmd(self,cmdstr,conn):
        result = os.popen(cmdstr.strip())
        conn.send("\r\nResult:"+cmdstr.strip()+'\r\n')
        for line in result:
            conn.send(line.strip()+'\r\n')
        conn.send('cmd>')    
        return result
    
    def threadrun(self,func_name,cmdstr,socketcon):
        threading.Thread(target = func_name, args = (cmdstr,socketcon), name = 'thread-cmd-' + str(int(time.time()))).start()
        
    def handlechild(self,clientsock):
        cmd = ''
        while 1:
            try:
                cmd += clientsock.recv(1024)
            except:
                clientsock.close()
                break
            if not cmd:
                break
            if cmd.endswith('\n'):
                if cmd.strip() == "start":
                    self.threadrun(self.excutecmd,'wscript.exe dailyrun.vbs -autorun',clientsock)
                if cmd.startswith("kill "):
                    cmdlist = cmd.strip().split(' ')
                    if len(cmdlist)>2:
                        clientsock.send("too long param!")
                    else:
                        cmdline = "taskkill /F /FI \"IMAGENAME eq "+cmdlist[1]+"\""
                        self.threadrun(self.excutecmd,cmdline,clientsock)
                if cmd.strip()== "rerun":#rerun dailyrun
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq python.exe\"',clientsock)
                    time.sleep(5)
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq wscript.exe\"',clientsock)
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq sogouexplorer.exe\"',clientsock)
                    time.sleep(2)
                    self.threadrun(self.excutecmd,'wscript.exe dailyrun.vbs -autorun',clientsock)
                if cmd.strip()== "stop":#stop dailyrun
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq python.exe\"',clientsock)
                    time.sleep(5)
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq wscript.exe\"',clientsock)
                    self.threadrun(self.excutecmd,'taskkill /F /FI \"IMAGENAME eq sogouexplorer.exe\"',clientsock)                  
                self.threadrun(self.excutecmd,cmd,clientsock)
                clientsock.send('cmd>')
                cmd=''    
    
    def main(self):
        HOST = ''                 # Symbolic name meaning all available interfaces
        PORT = 5985              # Arbitrary non-privileged port
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind((HOST, PORT))
        s.listen(1)
        while True:
            try:
                conn, addr = s.accept()
                conn.send("Welcome to connect "+socket.gethostname()+".\r\n")
                conn.send("""This is DailyRun Reporter:\r\nUser the following command:\r\n1. start : to start dailyrun script.\r\n2. kill XXX.exe: to kill XXX.exe process.\r\n3. rerun : to kill dailyrun script and then rerun it.\r\n4. stop : to stop automation.\r\n5. other command in windows.\r\n""")
                conn.send('cmd>')
            except:
                continue
            threading.Thread(target = self.handlechild, args = [conn], name = 'thread-cmd-' + str(int(time.time()))).start()
            
if __name__=='__main__':
    dailyruner = DailyrunReporter()
    dailyruner.main()
